#!/bin/bash

# 1. 查询当前TCP加速状态
get_tcpaccel_running_status() {
    local tcpaccel_status=$(ps -ef | grep td_tunnel_tcp | grep -v grep | wc -l)
    if [ $tcpaccel_status -eq 0 ]; then
        echo "stop"
    else
        echo "run"
    fi
}
# 2. 查询当前版本号
TCPACCEL_VERSION_STR="1.3.0"
# 3. 查询当前UE数量
get_tcpaccel_ue_count() {
    local iptables_prerouting_rules=$(sudo iptables-nft -t nat -nL PREROUTING | grep TCP_)
    # local iptables_prerouting_rules=$(cat ../logs/iptables-nft_test.txt | grep TCP_)
    declare -A ip_count
    local ue_count
    while IFS= read -r tcp_rule; do
        # echo "tcp_rule:$tcp_rule"
        # 你可以在这里继续处理每一行的内容
        local ip=$(echo $tcp_rule | awk -F "_" '{print $2}')
        # echo $ip
        if [ -z "${ip_count[$ip]}" ]; then
            ip_count["$ip"]=1
            ue_count=$((ue_count+1))
        else
            ((ip_count["$ip"]++))
        fi
    done <<< "$iptables_prerouting_rules"
    echo $ue_count
}
# 4. 查询当前TCP连接数量 (传参可选，不传参则查询所有svn的总链接数)
get_tcpaccel_conn_count() {
    local for_svn=$1
    local connt_total=0
    local count_for_svn
    local folder_list=$(ls -d ../logs/*/)
    # echo "file_list: $file_list"
    for folder in $folder_list; do
        # echo "folder: $folder"
        if [[ "$folder" =~ vrf([0-9]+)\/ ]]; then
            local svn_conn_count=0
            local vrf_number=${BASH_REMATCH[1]}
            # echo "路径 $folder 是合法的，vrf 后面的部分是数值 $vrf_number"
            local file_list=$(ls $folder | grep tunnel_server_.*_statistics.log)
            for file in $file_list; do
                # echo "file: $file"
                local connect_num=$(( $(cat $folder$file | wc -l) - 2 ))
                # echo "connect_num: $connect_num"
                svn_conn_count=$(( $svn_conn_count + $connect_num ))
            done
            connt_total=$(( $connt_total + $svn_conn_count ))
            local vrf_conn_str="svn$vrf_number:$svn_conn_count"
            # echo $vrf_conn_str
            if [ -z "$count_for_svn" ]; then
                count_for_svn=$vrf_conn_str
            else
                count_for_svn=$count_for_svn","$vrf_conn_str
            fi
        fi
    done
    if [ -z "$for_svn" ]; then
        echo $connt_total
    else 
        echo $count_for_svn
    fi
}


if [ $# -lt 1 ]; then
    echo "failed"
    echo "err! Usage: $0 [status/version/ue_count/connect_count/connect_count_svn]"
    exit 1
fi

if [ "$1" == "status" ]; then
    get_tcpaccel_running_status
elif [ "$1" == "version" ]; then
    echo $TCPACCEL_VERSION_STR
elif [ "$1" == "ue_count" ]; then
    get_tcpaccel_ue_count
elif [ "$1" == "connect_count" ]; then
    get_tcpaccel_conn_count
elif [ "$1" == "connect_count_svn" ]; then
    get_tcpaccel_conn_count "for_svn"
else
    echo "failed"
    echo "err! Usage: $0 [status/version/ue_count/connect_count/connect_count_svn]"
    exit 1
fi